package util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class StrutsConfig {
	public static Map<String,XmlBean> loadStrutsConfig(String configPath){
		Map<String,XmlBean> actionMap = new HashMap<String, XmlBean>();
		try{
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(new File(configPath));
			Element root = doc.getRootElement();
			Element beanRoot = root.getChild("form-beans");
			List<Element> beans = beanRoot.getChildren("form-bean");
			Element actionRoot = root.getChild("action-mapping");
			List<Element> actions = actionRoot.getChildren("action");
			for (Element element : actions) {
				XmlBean action = new XmlBean();
				action.setFormName(element.getAttributeValue("name"));
				for (Element bean : beans) {
					if(bean.getAttributeValue("name").equals(action.getFormName())){
						action.setFormType(bean.getAttributeValue("type"));
					}
				}
				action.setActionType(element.getAttributeValue("type"));
				action.setActionPath(element.getAttributeValue("path"));
				Map<String,String> forwardMap = new HashMap<String, String>();
				List<Element> forwards = element.getChildren();
				for (Element e : forwards) {
					forwardMap.put(e.getAttributeValue("name"), e.getAttributeValue("value"));
				}
				action.setActionForwards(forwardMap);
				actionMap.put(action.getActionPath(),action);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return actionMap;
	}
}
